package com.imooc.coupon.executor.impl;

import com.imooc.coupon.constant.RuleFlag;
import com.imooc.coupon.executor.AbstractExecutor;
import com.imooc.coupon.vo.CouponTemplateSDK;
import com.imooc.coupon.vo.SettlementInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * <h1>立减优惠券结算规则执行器</h1>
 * Created by Qinyi.
 */
@Slf4j
@Component
public class LiJianExecutor extends AbstractExecutor {

    /**
     * <h2>规则类型标记</h2>
     * @return {@link RuleFlag}
     */
    @Override
    public RuleFlag ruleConfig() {
        return RuleFlag.LIJIAN;
    }

    /**
     * <h2>优惠券规则的计算</h2>
     * @param settlement {@link SettlementInfo} 包含了选择的优惠券
     * @return {@link SettlementInfo} 修正过的结算信息
     */
    @Override
    public SettlementInfo computeRule(SettlementInfo settlement) {
        // 商品总额
        double goodsSum = retain2Decimals(goodsCostSum(settlement.getGoodsInfos()));

        // 商品类型不匹配
        SettlementInfo notSatifySettlement = processGoodsTypeNotSatisfy(settlement, goodsSum);
        if(notSatifySettlement!=null){
            log.debug("ManJian Template Is Not Match To GoodsType!");
            return notSatifySettlement;
        }

        // 立减优惠券直接使用, 没有门槛
        CouponTemplateSDK templateSDK = settlement.getCouponAndTemplateInfos().get(0).getTemplate();
        double quota = (double) templateSDK.getRule().getDiscount().getQuota();  // 折扣

        double cost = goodsSum - quota > minCost() ? goodsSum - quota : minCost();
        settlement.setCost(retain2Decimals(cost));
        log.debug("Use LiJian Coupon Make Goods Cost From {} To {}",
                goodsSum, settlement.getCost());

        return settlement;
    }
}
